package twel.probenprophet.helden.heroes.helden5;

import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import twel.probenprophet.base.exceptions.ProbenprophetException;

public class XmlReaderHelper {

	public Collection<Element> getChildren(Element element, String childrenName) {
		List<Element> children = new ArrayList<Element>();

		NodeList childrenNodes = element.getElementsByTagName(childrenName);
		for (int i = 0; i < childrenNodes.getLength(); i++) {
			Element child = (Element) childrenNodes.item(i);
			children.add(child);
		}

		return children;
	}

	public Collection<Element> getChildrenInWrapperElement(Element element, String childrenName, String wrapperName) {
		Element wrapperElement = getSingleChild(element, wrapperName);

		return getChildren(wrapperElement, childrenName);
	}

	public Element getSingleChild(Element element, String childName) {
		NodeList childNodes = element.getElementsByTagName(childName);

		if (childNodes.getLength() == 0) {
			throw new IllegalStateException("no child element found");
		}

		if (childNodes.getLength() > 1) {
			throw new IllegalStateException("more than one child element found");
		}

		return (Element) childNodes.item(0);
	}

	public Element getRootElement(Reader reader) {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		Document document = null;

		try {
			DocumentBuilder builder = factory.newDocumentBuilder();
			document = builder.parse(new InputSource(reader));
		} catch (ParserConfigurationException e) {
			reThrowAsRuntimeException(e);
		} catch (SAXException e) {
			reThrowAsRuntimeException(e);
		} catch (IOException e) {
			reThrowAsRuntimeException(e);
		}

		return document.getDocumentElement();
	}

	private void reThrowAsRuntimeException(Exception e) {
		throw new ProbenprophetException("loading heroes failed", e);
	}
}
